import pandas as pd
import json
import os

BASE_PATH = "./zhaopin_system/data/"


def clean_data(file_path):
    """清洗原始JSON数据，提取核心字段"""
    with open(file_path, "r", encoding="utf-8") as f:
        data = json.loads(f.read())["data"]["list"]
    df = pd.DataFrame(data)
    # 提取关键列并重命名
    df = df[["companyName", "name", "salaryReal", "workCity", "companySize", "publishTime"]].rename(
        columns={"name": "job_title", "salaryReal": "salary_range"}
    )
    # 处理薪资：拆分最低/最高薪资
    df[["low_salary", "high_salary"]] = df["salary_range"].str.split("-", expand=True).astype(int)
    df["average_salary"] = (df["low_salary"] + df["high_salary"]) / 2
    # 处理发布时间
    df["publish_time"] = pd.to_datetime(df["publishTime"]).dt.date
    return df.drop(columns=["publishTime", "salary_range"])


def analyze_salary_trend(df):
    """分析薪资趋势：按发布时间统计平均薪资"""
    return df.groupby("publish_time")["average_salary"].mean().reset_index()


def analyze_company_size(df):
    """分析公司规模分布：统计各规模岗位数量占比"""
    return df["companySize"].value_counts(normalize=True).mul(100).round(2).astype(str) + "%"


def analyze_work_city(df):
    """分析工作城市分布"""
    return df["workCity"].value_counts()


def main():
    print("=== 智联招聘数据分析工具 ===")

    # 获取可用页码列表
    available_pages = []
    for file in os.listdir(BASE_PATH):
        if file.startswith("raw_data_page") and file.endswith(".json"):
            try:
                page_num = int(file.split("_")[-1].split(".")[0].replace("page", ""))
                available_pages.append(page_num)
            except:
                continue

    if not available_pages:
        print(f"错误：{BASE_PATH} 目录下未找到数据文件！")
        return

    print(f"找到以下页码的数据：{sorted(available_pages)}")

    # 用户选择页码
    while True:
        try:
            page = int(input(f"请输入要分析的页码（1-{max(available_pages)}）："))
            if page not in available_pages:
                print(f"错误：页码 {page} 不存在！")
                continue
            break
        except ValueError:
            print("请输入有效的整数页码！")

    # 加载数据
    raw_file = f"{BASE_PATH}raw_data_page{page}.json"
    cleaned_df = clean_data(raw_file)
    print(f"\n[SUCCESS] 已加载第{page}页数据，共 {len(cleaned_df)} 条记录")

    # 分析选项菜单
    while True:
        print("\n请选择分析类型：")
        print("1. 薪资趋势分析")
        print("2. 公司规模分布")
        print("3. 工作城市分布")
        print("4. 查看完整数据")
        print("0. 退出程序")

        choice = input("请输入选项（0-4）：")

        if choice == "1":
            salary_trend = analyze_salary_trend(cleaned_df)
            print("\n薪资趋势分析：")
            print(salary_trend)

        elif choice == "2":
            size_distribution = analyze_company_size(cleaned_df)
            print("\n公司规模分布：")
            print(size_distribution)

        elif choice == "3":
            city_distribution = analyze_work_city(cleaned_df)
            print("\n工作城市分布：")
            print(city_distribution)

        elif choice == "4":
            print("\n完整数据预览：")
            print(cleaned_df.to_csv(sep="\t", na_rep="nan"))

        elif choice == "0":
            print("感谢使用，再见！")
            break

        else:
            print("无效选项，请重新输入！")


if __name__ == "__main__":
    main()